<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24"> </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <a-tabs v-model="activeKey" @change="handleChangeTab">
      <a-tab-pane key="notGenerated" tab="未生成">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="loadNotGeneratedData">
            <a-row :gutter="24">
              <a-col :span="24" style="margin-top: 10px">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button @click="addDeficitPick" type="primary" icon="plus">添加</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float: right">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item, index) in defColumns">
                      <template v-if="item.key !== 'rowIndex' && item.dataIndex !== 'action'">
                        <a-col :span="12"
                          ><a-checkbox :value="item.dataIndex"
                            ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                        ></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>
          </span>
        </div>
        <!-- table区域-begin -->
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap"
            :scroll="{ x: true }"
            :columns="waitColumns"
            :dataSource="dataSource"
            :pagination="{
              ...tempSaveTable.ipagination,
              onChange: handleTempSavePageChange, // 监听页码变化
              onShowSizeChange: handleTempSavePageSizeChange, // 监听每页数量变化
            }"
            :loading="loading"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          >
          </a-table>
        </div>
      </a-tab-pane>
      <a-tab-pane key="approved" tab="已审批">
        <div
          class="table-page-search-wrapper"
          style="display: flex; align-items: center; padding-top: 10px; padding-bottom: 24px; gap: 16px"
        >
          <a-form-item label="制单日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date
              placeholder="请选择开始日期"
              class="query-group-cust"
              v-model="queryParamApproved.createTime_begin"
            ></j-date>
            <span class="query-group-split-cust"></span>
            <j-date
              placeholder="请选择结束日期"
              class="query-group-cust"
              v-model="queryParamApproved.createTime_end"
            ></j-date>
          </a-form-item>
          <a-button type="primary" @click="loadApprovedData" icon="search" style="margin-top: -3px">查询</a-button>
        </div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
          <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
          >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          <span style="float: right">
            <a-popover title="自定义列" trigger="click" placement="leftBottom">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row style="width: 400px">
                    <template v-for="(item, index) in defColumns">
                      <template v-if="item.key !== 'rowIndex' && item.dataIndex !== 'action'">
                        <a-col :span="12"
                          ><a-checkbox :value="item.dataIndex"
                            ><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox
                        ></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />设置</a>
            </a-popover>
          </span>
        </div>
        <a-table
          ref="approvedTable"
          size="middle"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{ x: true }"
          :columns="columns"
          :dataSource="approvedTable.dataSource"
          :pagination="approvedTable.ipagination"
          :loading="approvedTable.loading"
          :rowSelection="{
            selectedRowKeys: approvedTable.selectedRowKeys,
            onChange: onDeficitPickSelectChangeApproved,
            type: 'radio',
          }"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="handleDetail(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="printPreview(record)">单据打印</a>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <tsl-pro-deficit-pick-bill-modal ref="modalForm" @ok="modalFormOk" />
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import TslProDeficitPickBillModal from './modules/TslProDeficitPickBillModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import '@/assets/less/TableExpand.less'
import ActApplyBtn from '@views/flowable/components/ActApplyBtn.vue'
import { getAction, postAction } from '@api/manage'
import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'
import { deepClone, getDate } from '../../utils'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import store from '@/store'

export default {
  name: 'TslProSampleDeficitBillList',
  mixins: [JeecgListMixin, JVxeTableModelMixin],
  components: {
    TslProDeficitPickBillModal,
    ActApplyBtn,
    ActHistoricDetailBtn,
  },
  data() {
    return {
      refKeys: ['unDetail', 'noMakeDetail', 'tempSaveDetail', 'approvedDetail'],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 28%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      productType: 0,
      billType: 'sample',
      orderCode: '',
      description: '领料赤字单管理页面',
      serviceName: 'TslProDeficitPickBillService',
      activeKey: 'notGenerated',
      notGeneratedList: [],
      waitColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '样品领料单号',
          key: 'pickCode',
          dataIndex: 'pickCode',
          type: JVXETypes.normal,
          align: 'center',
          width: 120,
          sorter: (a, b) => a.pickCode.localeCompare(b.pickCode, 'en'),
        },
        {
          title: '客户物料编码',
          key: 'customCode',
          type: JVXETypes.normal,
          align: 'center',
          width: '140px',
          defaultValue: '',
        },
        {
          title: '物料编码',
          key: 'productCode',
          dataIndex: 'productCode',
          type: JVXETypes.normal,
          align: 'center',
          width: 120,
          defaultValue: '',
        },
        {
          title: '物料名称',
          key: 'productBatchNo',
          dataIndex: 'productBatchNo',
          type: JVXETypes.normal,
          align: 'center',
          width: 300,
          defaultValue: '',
        },
        {
          title: '规格型号',
          key: 'materialSpec',
          dataIndex: 'materialSpec',
          type: JVXETypes.normal,
          align: 'center',
          width: 100,
        },
        {
          title: '主单位',
          key: 'meUnit_dictText',
          dataIndex: 'meUnit_dictText',
          dictCode: 'ji_unit',
          type: JVXETypes.select,
          align: 'center',
          width: 100,
          disabled: true,
        },
        {
          title: '申请数量',
          key: 'applyQuantity',
          dataIndex: 'applyQuantity',
          align: 'center',
          width: 120,
        },
        {
          title: '领料人',
          align: 'center',
          dataIndex: 'pickBy',
        },
        {
          title: '领料部门',
          align: 'center',
          dataIndex: 'pickOrgCode_dictText',
        },
        {
          title: '领料日期',
          align: 'center',
          dataIndex: 'pickDate',
          sorter: (a, b) => a.pickDate.localeCompare(b.pickDate, 'en'),
        },
        {
          title: '制单人',
          align: 'center',
          dataIndex: 'createBy_dictText',
        },
        {
          title: '制单部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText',
        },
        {
          title: '制单日期',
          align: 'center',
          dataIndex: 'createTime',
          sorter: (a, b) => a.createTime.localeCompare(b.createTime, 'en'),
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          key: 'remark',
          type: JVXETypes.normal,
        },
      ],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '样品领料赤字单号',
          key: 'billCode',
          dataIndex: 'billCode',
          type: JVXETypes.normal,
          align: 'center',
          width: 120,
          sorter: (a, b) => a.code.localeCompare(b.code, 'en'),
        },
        {
          title: '样品领料单号',
          key: 'pickCode',
          dataIndex: 'pickCode',
          type: JVXETypes.normal,
          align: 'center',
          width: 120,
          sorter: (a, b) => a.pickCode.localeCompare(b.pickCode, 'en'),
        },
        {
          title: '客户物料编码',
          key: 'customCode',
          type: JVXETypes.normal,
          align: 'center',
          width: '140px',
          defaultValue: '',
        },
        {
          title: '物料编码',
          key: 'productCode',
          dataIndex: 'productCode',
          type: JVXETypes.normal,
          align: 'center',
          width: 120,
          defaultValue: '',
        },
        {
          title: '物料名称',
          key: 'productBatchNo',
          dataIndex: 'productBatchNo',
          type: JVXETypes.normal,
          align: 'center',
          width: 300,
          defaultValue: '',
        },
        {
          title: '规格型号',
          key: 'materialSpec',
          dataIndex: 'materialSpec',
          type: JVXETypes.normal,
          align: 'center',
          width: 100,
        },
        {
          title: '主单位',
          key: 'meUnit_dictText',
          dataIndex: 'meUnit_dictText',
          dictCode: 'ji_unit',
          type: JVXETypes.select,
          align: 'center',
          width: 100,
          disabled: true,
        },
        {
          title: '退料数量',
          key: 'backQuantity',
          dataIndex: 'backQuantity',
          align: 'center',
          width: 120,
        },
        {
          title: '领料人',
          align: 'center',
          dataIndex: 'pickBy',
        },
        {
          title: '领料部门',
          align: 'center',
          dataIndex: 'pickOrgCode_dictText',
          width: 120,
        },
        {
          title: '领料日期',
          align: 'center',
          dataIndex: 'pickDate',
        },
        {
          title: '制单人',
          align: 'center',
          dataIndex: 'createBy_dictText',
        },
        {
          title: '制单部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText',
        },
        {
          title: '制单日期',
          align: 'center',
          dataIndex: 'createTime',
          sorter: (a, b) => a.createTime.localeCompare(b.createTime, 'en'),
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          key: 'remark',
          type: JVXETypes.normal,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 60,
          scopedSlots: { customRender: 'action' },
        },
      ],
      approvedTable: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      tempSaveTable: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        dataSource: [],
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      url: {
        waitSampleList: 'pro/tslProDeficitPickBill/waitSampleList',
        detailList: '/pro/tslProDeficitPickBill/detailList',
        approval: '/pro/tslProDeficitPickBill/approval',
        close: '/pro/tslProDeficitPickBill/close',
        delete: '/pro/tslProDeficitPickBill/delete',
        deleteBatch: '/pro/tslProDeficitPickBill/deleteBatch',
        exportXlsUrl: '/pro/tslProDeficitPickBill/exportXls',
        importExcelUrl: 'pro/tslProDeficitPickBill/importExcel',
        TslProDeficitPickBillDetail: '/pro/tslProDeficitPickBill/queryTslProDeficitPickBillInfoByMainId',
      },
      dictOptions: {},
      queryParamApproved: {
        createTime_begin: undefined,
        createTime_end: undefined,
      },
      settingColumns: [],
    }
  },
  created() {
    this.queryParamApproved.createTime_begin = getDate('day', -7)
    this.queryParamApproved.createTime_end = getDate('day', 0)
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    // 暂存中页：处理页码变化
    handleTempSavePageChange(page, pageSize) {
      this.tempSaveTable.ipagination.current = page
      this.tempSaveTable.ipagination.pageSize = pageSize
      this.loadTempSaveData()
    },
    // 暂存中页：处理每页数量变化
    handleTempSavePageSizeChange(page, pageSize) {
      this.tempSaveTable.ipagination.current = page
      this.tempSaveTable.ipagination.pageSize = pageSize
      this.loadTempSaveData()
    },
    // 已审批页：处理页码变化
    handleApprovedPageChange(page, pageSize) {
      this.approvedTable.ipagination.current = page
      this.approvedTable.ipagination.pageSize = pageSize
      this.loadApprovedData()
    },
    // 已审批页：处理每页数量变化
    handleApprovedPageSizeChange(page, pageSize) {
      this.approvedTable.ipagination.current = page
      this.approvedTable.ipagination.pageSize = pageSize
      this.loadApprovedData()
    },
    onDeficitPickSelectChangeApproved(selectedRowKeys, selectedRows) {
      this.approvedTable.selectedRowKeys = selectedRowKeys
    },
    addDeficitPick(rows) {
      if (!this.selectedRowKeys || this.selectedRowKeys.length == 0) {
        this.$message.error('请至少选择一条领料单！')
        return
      }
      let selectedRows = []
      this.dataSource.forEach((element) => {
        if (this.selectedRowKeys.includes(element.id)) {
          selectedRows.push(element)
        }
      })
      this.$refs.modalForm.add(selectedRows, this.billType)
      this.$refs.modalForm.title = '添加'
      this.$refs.modalForm.disableSubmit = false
    },
    loadNotGeneratedData() {
      this.selectedRowKeys = []
      this.dataSource = []
      this.loading = true
      getAction(this.url.waitSampleList, {
        pageNo: this.tempSaveTable.ipagination.current,
        pageSize: this.tempSaveTable.ipagination.pageSize,
      })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.tempSaveTable.ipagination.total = res.result.total
            } else {
              this.tempSaveTable.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    loadApprovedData() {
      this.approvedTable.loading = true
      this.queryParamApproved.billType = this.billType
      this.queryParamApproved.pageNo = this.approvedTable.ipagination.current
      this.queryParamApproved.pageSize = this.approvedTable.ipagination.pageSize
      getAction(this.url.detailList, this.queryParamApproved)
        .then((res) => {
          if (res.success) {
            this.approvedTable.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.approvedTable.ipagination.total = res.result.total
            } else {
              this.approvedTable.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.approvedTable.loading = false
        })
    },
    async loadData() {
      //分别根据单据状态查询结果并将其放在
      this.handleChangeTab()
    },
    handleChangeTab() {
      switch (this.activeKey) {
        case 'notGenerated':
          this.loadNotGeneratedData()
          break
        case 'approved':
          this.loadApprovedData()
          break
        default:
          break
      }
    },
    printPreview(record) {
      let token = store.getters.token
      let id = record.billId
      window.open(`${window._CONFIG['domianURL']}/jmreport/view/1098841336191471616?token=${token}&id=${id}`, '_blank')
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
::v-deep .ant-table-tbody tr {
  height: 36px !important;
}
</style>
